# import re
#
# import fitz
#
# from tests.base_test import base_test_case
#
# logger = base_test_case.get_logger(__name__)
# TEST_DATA_DIR = base_test_case.test_data_dir
# OUTPUT_DATA_DIR = base_test_case.output_data_dir
#
#
# # ------------------------------------------------------------
# # 动态页码提取函数（简化版，无需坐标）
# # ------------------------------------------------------------
# def robust_get_page_number(page, area_page_l=None, area_page_r=None):
#     """
#     尝试从页面中提取页码，优先使用固定区域（如果提供），否则动态检测。
#     此处仅实现动态检测部分。
#     """
#     # 如果提供了固定区域，可在此扩展（略）
#     # 本测试 focus 在 area_page_l/r = None 的情况
#
#     blocks = page.get_text("dict").get("blocks", [])
#     mediabox = page.rect
#     page_height = mediabox.height
#     candidates = []
#
#     for block in blocks:
#         if "lines" not in block:
#             continue
#         for line in block["lines"]:
#             for span in line["spans"]:
#                 text = span["text"].strip()
#                 if not text:
#                     continue
#
#                 # 提取连续数字（页码通常是纯数字）
#                 num_match = re.search(r'\d+', text)
#                 if not num_match:
#                     continue
#
#                 bbox = fitz.Rect(span["bbox"])
#                 y_center = (bbox.y0 + bbox.y1) / 2
#
#                 # 判断是否在底部 80pt 或顶部 80pt 区域（常见页码位置）
#                 in_footer = (page_height - y_center) < 80
#                 in_header = y_center < 80
#
#                 if in_footer or in_header:
#                     try:
#                         num = int(num_match.group())
#                         # 简单打分：越靠近边缘越可能是页码
#                         score = 0
#                         if in_footer:
#                             score += 100 - (page_height - y_center)
#                         if in_header:
#                             score += y_center
#                         candidates.append((num, score))
#                     except ValueError:
#                         continue
#
#     if candidates:
#         # 返回得分最高的页码
#         best = max(candidates, key=lambda x: x[1])
#         return best[0]
#
#     return None
#
#
# # 测试方案
# def extract_page_candidates(page):
#     """
#     提取一页中所有可能的页码候选（含位置得分）
#     返回列表：[(num, score, is_footer)]
#     """
#     blocks = page.get_text("dict").get("blocks", [])
#     mediabox = page.rect
#     page_height = mediabox.height
#     candidates = []
#
#     for block in blocks:
#         if "lines" not in block:
#             continue
#         for line in block["lines"]:
#             for span in line["spans"]:
#                 text = span["text"].strip()
#                 if not text:
#                     continue
#
#                 # 允许包含数字的文本（如 "Page 3"、"–181–"）
#                 num_match = re.search(r'\d+', text)
#                 if not num_match:
#                     continue
#
#                 try:
#                     num = int(num_match.group())
#                 except ValueError:
#                     continue
#
#                 # 跳过明显不合理的页码（如年份、章节号）
#                 if num > 2000 or num <= 0:
#                     continue
#
#                 bbox = fitz.Rect(span["bbox"])
#                 y_center = (bbox.y0 + bbox.y1) / 2
#                 in_footer = (page_height - y_center) < 80
#                 in_header = y_center < 80
#
#                 if in_footer or in_header:
#                     score = 0
#                     if in_footer:
#                         score += 100 - (page_height - y_center)  # 越靠下分越高
#                     if in_header:
#                         score += y_center  # 越靠上分越高（但通常页脚更可信）
#                     # 页脚优先：额外加分
#                     if in_footer:
#                         score += 50
#                     candidates.append((num, score, in_footer))
#
#     # 按得分降序
#     candidates.sort(key=lambda x: x[1], reverse=True)
#     return candidates
#
#
# def fallback_extract_small_numbers(page, max_num=50):
#     """全文扫描，提取 1~max_num 的数字作为最后 fallback"""
#     blocks = page.get_text("dict").get("blocks", [])
#     small_nums = []
#     for block in blocks:
#         for line in block.get("lines", []):
#             for span in line.get("spans", []):
#                 text = span["text"].strip()
#                 match = re.search(r'\d+', text)
#                 if match:
#                     try:
#                         num = int(match.group())
#                         if 1 <= num <= max_num:
#                             small_nums.append(num)
#                     except ValueError:
#                         continue
#     return min(small_nums) if small_nums else None
#
#
# def robust_get_page_number(page, area_page_l=None, area_page_r=None):
#     """
#     保留原始逻辑，但为后续全局校正准备候选列表。
#     此函数仅用于提取候选，最终页码由 post_process_page_numbers 决定。
#     """
#     if area_page_l or area_page_r:
#         # 固定区域逻辑（略）
#         pass
#
#     candidates = extract_page_candidates(page)
#     if candidates:
#         return candidates[0][0]  # 返回最高分候选（临时）
#     return fallback_extract_small_numbers(page)
#
#
# def post_process_page_numbers(doc, initial_numbers):
#     """
#     全局校正页码序列：
#     - 假设真实页码是连续递增的小整数（1,2,3...）
#     - 若某页数字突变（如 1 → 181），则尝试用其他候选或 fallback
#     """
#     n = len(initial_numbers)
#     corrected = [None] * n
#
#     # 第一步：找出最可能的起始页码（最小正整数）
#     valid_nums = [x for x in initial_numbers if x is not None and 1 <= x <= 100]
#     start_guess = min(valid_nums) if valid_nums else 1
#
#     # 第二步：尝试从每一页的候选中选择符合连续性的数字
#     for i in range(n):
#         page = doc[i]
#         candidates = extract_page_candidates(page)
#
#         target = start_guess + i  # 期望的页码
#
#         # 优先找等于 target 的候选
#         for num, score, is_footer in candidates:
#             if num == target:
#                 corrected[i] = num
#                 break
#         else:
#             # 次选：找接近 target 的小数字
#             close_candidates = [num for num, _, _ in candidates if abs(num - target) <= 2 and 1 <= num <= 100]
#             if close_candidates:
#                 corrected[i] = min(close_candidates)  # 选最小的
#             else:
#                 # 最后 fallback
#                 corrected[i] = fallback_extract_small_numbers(page) or target
#
#     return corrected
#
#
# def main(input_pdf):
#     if not input_pdf.exists():
#         print(f"❌ PDF 文件不存在: {input_pdf}")
#         return
#
#     print(f"📄 正在打开 PDF: {input_pdf}")
#     try:
#         with fitz.open(input_pdf) as doc:
#             total = doc.page_count
#             print(f"📄 共 {total} 页\n")
#
#             # 第一阶段：初步提取
#             raw_numbers = []
#             for i in range(total):
#                 page = doc[i]
#                 num = robust_get_page_number(page)
#                 raw_numbers.append(num)
#
#             print("原始识别结果:", raw_numbers)
#
#             # 第二阶段：全局校正
#             corrected_numbers = post_process_page_numbers(doc, raw_numbers)
#
#             for i, (raw, corr) in enumerate(zip(raw_numbers, corrected_numbers)):
#                 print(f"第 {i + 1:2d} 页 → 原始: {raw:4}, 校正: {corr:4}")
#
#     except Exception as e:
#         print(f"❌ 处理失败: {e}")
#         import traceback
#         traceback.print_exc()
#
#
# if __name__ == "__main__":
#     # 动态页码提取函数（简化版，无需坐标）
#     # TODO 功能待完善
#     input_pdf = TEST_DATA_DIR / "1715339805571.pdf"
#     main(input_pdf)
